package org.mock.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.mock.common.ResultBaiFenHui;
import org.mock.dto.BaifenhuiOrderBaseDTO;
import org.mock.dto.BaifenhuiOrderProductDTO;
import org.mock.entity.BaifenhuiOrderBase;
import org.mock.entity.BaifenhuiProduct;
import org.mock.enums.BaiFenHuiOrderStatus;
import org.mock.enums.BaiFenHuiOrderType;
import org.mock.enums.BaiFenHuiProductState;
import org.mock.mapper.BaifenhuiProductMapper;
import org.mock.request.baiFenHui.CreateRechargeOrderRequest;
import org.mock.request.baiFenHui.GoodInfoRequest;
import org.mock.request.baiFenHui.ProductVo;
import org.mock.response.baiFenHui.CreateRechargeOrderResponse;
import org.mock.service.BaifenhuiOrderBaseService;
import org.mock.service.BaifenhuiOrderProductService;
import org.mock.service.BaifenhuiProductService;
import org.mock.dto.BaifenhuiProductDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.mock.common.Condition;
import org.mock.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import cn.hutool.core.util.StrUtil;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 服务实现类
 *
 * @author AI
 * @since 2025-05-21
 */
@Service
@AllArgsConstructor
@Slf4j
public class BaifenhuiProductServiceImpl implements BaifenhuiProductService {

    protected BaifenhuiProductMapper baifenhuiProductMapper;
    protected BaifenhuiOrderBaseService baifenhuiOrderBaseService;
    protected BaifenhuiOrderProductService baifenhuiOrderProductService;

    @Override
    public IPage<BaifenhuiProduct> page(BaifenhuiProductDTO dto) {
        IPage<BaifenhuiProduct> page = Condition.getPage(dto);
        QueryWrapper<BaifenhuiProduct> queryWrapper = Condition.getQueryWrapper(BeanCopyUtils.copy(dto, BaifenhuiProduct.class));
        if (StrUtil.isNotEmpty(dto.getColumn()) && StrUtil.isNotEmpty(dto.getKeywords())) {
            queryWrapper.like(dto.getColumn(), dto.getKeywords());
        }
        if (StrUtil.isNotEmpty(dto.getOrderAsc())) {
            queryWrapper.orderByAsc(dto.getOrderAsc());
        }
        if (StrUtil.isNotEmpty(dto.getOrderDesc())) {
            queryWrapper.orderByDesc(dto.getOrderDesc());
        }
        if (dto.getStartTime() != null) {
            queryWrapper.gt("created", dto.getStartTime());
        }
        if (dto.getEndTime() != null) {
            queryWrapper.lt("created", dto.getEndTime());
        }
        return baifenhuiProductMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<BaifenhuiProduct> list(BaifenhuiProductDTO dto) {
        QueryWrapper<BaifenhuiProduct> queryWrapper = Condition.getQueryWrapper(BeanCopyUtils.copy(dto, BaifenhuiProduct.class));
        if (StrUtil.isNotEmpty(dto.getColumn()) && StrUtil.isNotEmpty(dto.getKeywords())) {
            queryWrapper.like(dto.getColumn(), dto.getKeywords());
        }
        if (StrUtil.isNotEmpty(dto.getOrderAsc())) {
            queryWrapper.orderByAsc(dto.getOrderAsc());
        }
        if (StrUtil.isNotEmpty(dto.getOrderDesc())) {
            queryWrapper.orderByDesc(dto.getOrderDesc());
        }
        if (dto.getStartTime() != null) {
            queryWrapper.gt("created", dto.getStartTime());
        }
        if (dto.getEndTime() != null) {
            queryWrapper.lt("created", dto.getEndTime());
        }
        return baifenhuiProductMapper.selectList(queryWrapper);
    }

    @Override
    public Integer save(BaifenhuiProductDTO dto) {
        return baifenhuiProductMapper.insert(BeanCopyUtils.copy(dto, BaifenhuiProduct.class));
    }

    @Override
    public Integer updateById(BaifenhuiProductDTO dto) {
        return baifenhuiProductMapper.updateById(BeanCopyUtils.copy(dto, BaifenhuiProduct.class));
    }


    @Override
    public Integer deleteLogic(List<Integer> toIntList) {
        return baifenhuiProductMapper.deleteBatchIds(toIntList);
    }

    @Override
    public BaifenhuiProduct getOne(BaifenhuiProductDTO dto) {
        return baifenhuiProductMapper.selectOne(Condition.getQueryWrapper(BeanCopyUtils.copy(dto, BaifenhuiProduct.class)));
    }

    @Override
    public ResultBaiFenHui getGoodInfo(GoodInfoRequest request) {
        try {
            BaifenhuiProductDTO dto = new BaifenhuiProductDTO();
            dto.setItemId(request.getItemId());
            BaifenhuiProduct product = this.getOne(dto);
            JSONObject response = new JSONObject();
            response.put("product", product);
            return ResultBaiFenHui.success(response);
        } catch (Exception e) {
            log.error("异常：{}", e.getMessage(), e);
            return ResultBaiFenHui.error("999", e.getMessage());
        }
    }

    @Override
    public ResultBaiFenHui createRechargeOrder(CreateRechargeOrderRequest request) {
        try {
            log.info("开始创建订单！");

            //先校验是否已经存在订单
            String orderId = request.getOrderId();
            BaifenhuiOrderBaseDTO query = new BaifenhuiOrderBaseDTO();
            query.setOrderId(orderId);
            BaifenhuiOrderBase one = baifenhuiOrderBaseService.getOne(query);
            if (ObjectUtil.isNotEmpty(one)) {
                return ResultBaiFenHui.error("999", "订单已存在！orderId：" + orderId);
            }

            BaifenhuiOrderProductDTO orderProduct = new BaifenhuiOrderProductDTO();
            BaifenhuiOrderBaseDTO orderBase = new BaifenhuiOrderBaseDTO();

            List<ProductVo> productVoList = request.getProducts();
            ProductVo productVo = productVoList.get(0);
            Integer itemId = productVo.getItemId();
            BaifenhuiProductDTO productDTO = new BaifenhuiProductDTO();
            productDTO.setItemId(itemId);
            BaifenhuiProduct product = this.getOne(productDTO);

            //生成随机订单号，百分汇内部订单号
            String orderSn = "SN" + DateUtil.today() + IdUtil.objectId();
            orderBase.setOrderSn(orderSn);
            orderBase.setOrderId(orderId);
            orderBase.setOrderType(BaiFenHuiOrderType.RECHARGE.getValue());
            orderBase.setNote(request.getNote());
            orderBase.setAddTime(LocalDateTime.now());
            orderBase.setCustomerPhone(request.getShouhuo_phone());
            orderBase.setStatus(BaiFenHuiOrderStatus.TO_BE_CONFIRMED.getValue());
            orderBase.setOrderPrice(product.getSettlement());
            baifenhuiOrderBaseService.save(orderBase);

            orderProduct.setOrderId(orderId);
            orderProduct.setItemId(itemId);
            orderProduct.setName(product.getProductName());
            orderProduct.setNumber(1);
            orderProduct.setPrice(product.getSettlement());
            orderProduct.setState(BaiFenHuiProductState.TO_BE_SEND.getValue());
            orderProduct.setTotalPrice(product.getSettlement());
            baifenhuiOrderProductService.save(orderProduct);

            CreateRechargeOrderResponse response = new CreateRechargeOrderResponse();
            response.setOrder_sn(orderSn);
            response.setCreatetime(DateUtil.now());
            return ResultBaiFenHui.success(response);
        } catch (Exception e) {
            log.error("异常：{}", e.getMessage(), e);
            return ResultBaiFenHui.error("999", e.getMessage());
        }
    }
}
